package com.jie.server.mvc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jie.common.http.constant.HttpEntityClassNameConstant;
import com.jie.common.http.constant.HttpHeaderLineNameConstant;
import com.jie.common.http.constant.response.ServerResponseStatusConstant;
import com.jie.common.http.entity.response.HttpResponse;
import com.jie.common.util.JsonUtil;
import com.jie.server.core.ServerApplication;
import com.jie.server.core.entity.SessionNode;
import com.jie.server.core.util.NioUtil;
import com.jie.server.mvc.mapper.GroupRelevanceMapper;
import com.jie.server.mvc.mapper.UserMapper;
import com.jie.server.mvc.model.entity.GroupChat;
import com.jie.server.mvc.mapper.GroupChatMapper;
import com.jie.server.mvc.model.entity.GroupRelevance;
import com.jie.server.mvc.model.entity.User;
import com.jie.server.mvc.model.vo.GroupChatQueryVo;
import com.jie.server.mvc.model.vo.GroupChatVo;
import com.jie.server.mvc.service.GroupChatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 群聊表 服务实现类
 * </p>
 *
 * @author XieZhiJie
 * @since 2022-04-24
 */
@Service
public class GroupChatServiceImpl extends ServiceImpl<GroupChatMapper, GroupChat> implements GroupChatService {

    private final Logger logger = LoggerFactory.getLogger(GroupChatServiceImpl.class);

    private final GroupChatMapper groupChatMapper;

    private final GroupRelevanceMapper groupRelevanceMapper;

    private final UserMapper userMapper;

    @Autowired
    public GroupChatServiceImpl(
            GroupChatMapper groupChatMapper,
            GroupRelevanceMapper groupRelevanceMapper,
            UserMapper userMapper
    ) {
        this.groupChatMapper = groupChatMapper;
        this.groupRelevanceMapper = groupRelevanceMapper;
        this.userMapper = userMapper;
    }

    @Override
    public boolean chat(GroupChat groupChat) {
        // 1.判断发送用户是否在群中
        Integer sendUserId = groupChat.getSendUserId();
        Integer groupId = groupChat.getGroupId();
        QueryWrapper<GroupRelevance> groupRelevanceQueryWrapper = new QueryWrapper<>();
        groupRelevanceQueryWrapper.eq("user_id", sendUserId);
        groupRelevanceQueryWrapper.eq("group_id", groupId);
        if (this.groupRelevanceMapper.selectOne(groupRelevanceQueryWrapper) == null) {
            return false;
        } else if (groupChat.getChatMessage() == null || "".equals(groupChat.getChatMessage().trim())) {
            return false;
        }
        User sendUser = this.userMapper.selectById(groupChat.getSendUserId());
        // 2.插入数据库信息
        groupChat.setId(null);
        groupChat.setSendTime(LocalDateTime.now());
        groupChat.setSendUserIdent(sendUser.getUsername() + "(" + sendUser.getUserAccount() + ")");
        if (this.groupChatMapper.insert(groupChat) <= 0) {
            return false;
        }
        // 3.获取群组人员并判断是否在线, 在线则转发信息
        groupRelevanceQueryWrapper = new QueryWrapper<>();
        groupRelevanceQueryWrapper.eq("group_id", groupId);
        List<GroupRelevance> groupRelevanceList = this.groupRelevanceMapper.selectList(groupRelevanceQueryWrapper);
        try {
            GroupChatVo groupChatVo = new GroupChatVo();
            BeanUtils.copyProperties(groupChat, groupChatVo);
            groupChatVo.setSendUserId(sendUser.getUserId());
            groupChatVo.setSendUserAccount(sendUser.getUserAccount());
            groupChatVo.setSendUsername(sendUser.getUsername());
            HttpResponse httpResponse = new HttpResponse();
            httpResponse.addOneHeaderLine(HttpHeaderLineNameConstant.SERVER_RESPONSE_STATUS, ServerResponseStatusConstant.CHAT_FROM_GROUP_SUCCESS);
            httpResponse.addOneHeaderLine(HttpHeaderLineNameConstant.ENTITY_DATA_CLASS_NAME, HttpEntityClassNameConstant.JSON_STRING_CLASS_NAME);
            httpResponse.setEntity(JsonUtil.toJson(groupChatVo));
            for (GroupRelevance groupRelevance : groupRelevanceList) {
                if (Objects.equals(groupRelevance.getUserId(), sendUserId)) {
                    continue;
                }
                SessionNode sessionNode = ServerApplication.SESSION.get(groupRelevance.getUserId());
                if (sessionNode != null) {
                    NioUtil.sendMessage(groupRelevance.getUserId(), httpResponse);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return true;
    }

    @Override
    public Page<GroupChat> records(int userId, GroupChatQueryVo groupChatQueryVo) {
        // 1.查看当前用户是否在群中
        QueryWrapper<GroupRelevance> groupRelevanceQueryWrapper = new QueryWrapper<>();
        groupRelevanceQueryWrapper.eq("user_id", userId);
        groupRelevanceQueryWrapper.eq("group_id", groupChatQueryVo.getTargetGroupId());
        if (this.groupRelevanceMapper.selectOne(groupRelevanceQueryWrapper) == null) {
            return null;
        }
        // 2.分页查询
        Page<GroupChat> groupChatPage = new Page<>(groupChatQueryVo.getCurrent(), groupChatQueryVo.getLimit());
        QueryWrapper<GroupChat> groupChatQueryWrapper = new QueryWrapper<>();
        groupChatQueryWrapper.eq("group_id", groupChatQueryVo.getTargetGroupId());
        return this.groupChatMapper.selectPage(groupChatPage, groupChatQueryWrapper);
    }

}
